package com.jianan.mis.service;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.jianan.mis.data.dao.SchoolDao;
import com.jianan.mis.data.dao.base.PageControl;
import com.jianan.mis.data.domain.School;

public class SchoolServiceImpl implements SchoolService {

	private SchoolDao schoolDao;

	public void save(School school) {
		schoolDao.save(school);
	}
	
	public void update(School school) {
		schoolDao.saveOrUpdate(school);
	}
	
	public void remove(School school) {
		schoolDao.remove(school);
	}
	
	public List<School> getAll() {
		return schoolDao.getAll(School.class, "Name", true);
	}

	public void pageQuery(PageControl pageControl, Map conditions) {
		Criteria criteria = schoolDao.createCriteria(School.class);
		if (conditions.get("schoolName") != null) {
			String schoolName = (String) conditions.get("schoolName");
			criteria.add(Restrictions.like("Name", schoolName, MatchMode.ANYWHERE));
		}
		if (conditions.get("public") != null) {
			Boolean isPublic = (Boolean) conditions.get("public");
			criteria.add(Expression.eq("Public", isPublic));
		}
		if (conditions.get("property") != null) {
			String property = (String) conditions.get("property");
			criteria.add(Expression.eq("Property", property));
		}
		if (conditions.get("scholarship") != null) {
			Integer scholarship = (Integer) conditions.get("scholarship");
			if (scholarship.equals(0))
				criteria.add(Expression.isNotNull("Scholarship"));
			else if (scholarship.equals(1))
				criteria.add(Expression.isNull("Scholarship"));
		}
		if (conditions.get("countryId") != null) {
			Integer countryId = (Integer) conditions.get("countryId");
			criteria.add(Expression.eq("Country.id", countryId));
		}
		if (conditions.get("speciality") != null) {
			String speciality = (String) conditions.get("speciality");
			criteria.add(Restrictions.like("Speciality", speciality, MatchMode.ANYWHERE));
		}
		if (conditions.get("state") != null) {
			String state = (String) conditions.get("state");
			criteria.add(Restrictions.like("State", state, MatchMode.ANYWHERE));
		}
		criteria.addOrder(Order.asc("id"));
		pageControl = schoolDao.pagedQuery(criteria, pageControl);
	}

	public void setSchoolDao(SchoolDao schoolDao) {
		this.schoolDao = schoolDao;
	}

	@SuppressWarnings("unchecked")
	public List<School> findByName(String name) {
		Criteria criteria = schoolDao.createCriteria(School.class);
		criteria.add(Restrictions.like("Name", name, MatchMode.ANYWHERE));
		return criteria.list();
	}
	
}
